<template>
  <div>
    <el-card>
      <CategorySelector
        :isShowList="isShowList"
        @changeCategory="changeCategory"
      ></CategorySelector>
    </el-card>

    <el-card style="margin-top: 20px">
      <div v-show="isShowList">
        <!-- 列表页 -->
        <el-button type="primary" icon="el-icon-plus" @click="showAddDiv"
          >添加属性</el-button
        >
        <el-table :data="attrList" border style="width: 100%; margin: 20px 0">
          <el-table-column
            type="index"
            align="center"
            prop="prop"
            label="序号"
            width="80"
          >
          </el-table-column>

          <el-table-column prop="attrName" label="属性名称" width="150">
          </el-table-column>

          <el-table-column prop="prop" label="属性值列表" width="width">
            <template slot-scope="{ row }">
              <el-tag
                type="success"
                v-for="attrValue in row.attrValueList"
                :key="attrValue.id"
                >{{ attrValue.valueName }}</el-tag
              >
            </template>
          </el-table-column>

          <el-table-column prop="prop" label="操作" width="150">
            <template slot-scope="{ row }">
              <HintButton
                type="warning"
                icon="el-icon-edit"
                size="mini"
                title="修改"
                @click="showUpdateDIv(row)"
              ></HintButton>
              <el-popconfirm
                :title="`你确定删除${row.attrName}吗?`"
                @onConfirm="deleteAttr(row)"
              >
                <HintButton
                  slot="reference"
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  title="删除属性值"
                ></HintButton>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div v-show="!isShowList">
        <!-- 添加或修改页 -->
        <el-form :inline="true" :model="attrForm">
          <el-form-item label="属性名">
            <el-input
              v-model="attrForm.attrName"
              placeholder="请输入属性名"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="addAttrValue"
          :disabled="!attrForm.attrName"
          >添加属性值</el-button
        >
        <el-button @click="isShowList = true">取消</el-button>
        <el-table
          :data="attrForm.attrValueList"
          border
          style="width: 100%; margin: 20px 0"
        >
          <el-table-column
            type="index"
            align="center"
            prop="prop"
            label="序号"
            width="80"
          >
          </el-table-column>
          <el-table-column prop="prop" label="属性值名称" width="width">
            <!-- <template slot-scope="{row}">
              <el-input v-model="row.valueName" ></el-input>
            </template> -->
            <template slot-scope="{ row, $index }">
              <el-input
                v-if="row.isEdit"
                v-model="row.valueName"
                placeholder="请添加属性值"
                size="mini"
                :ref="$index"
                @blur="toLook(row)"
                @keyup.enter.native="toLook(row)"
              ></el-input>
              <span
                style="display: block; width: 100"
                @click="toEdit(row, $index)"
                v-else
                >{{ row.valueName }}</span
              >
            </template>
          </el-table-column>

          <el-table-column prop="prop" label="操作" width="width">
            <template slot-scope="{ row, $index }">
              <el-popconfirm
                :title="`你确定删除${row.valueName}吗`"
                @onConfirm="attrForm.attrValueList.splice($index, 1)"
              >
                <HintButton
                  slot="reference"
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  title="删除属性值"
                ></HintButton>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>

        <el-button
          type="primary"
          @click="save"
          :disabled="attrForm.attrValueList.length === 0"
          >保存</el-button
        >
        <el-button @click="isShowList = true">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import cloneDeep from "lodash/cloneDeep";
export default {
  name: "AttrList",
  data() {
    return {
      category1Id: "",
      category2Id: "",
      category3Id: "",
      attrList: [],

      isShowList: true,
      // 收集数据最终收集成什么样子是从接口文档来的
      attrForm: {
        attrName: "",
        attrValueList: [
          // {
          //   attrId: 0,
          //   id: 0,
          //   valueName: "string",
          // },
        ],
        categoryId: 0,
        categoryLevel: 3,
      },
    };
  },
  methods: {
    changeCategory({ categoryId, level }) {
      if (level === 1) {
        // 父组件获取到1级id要清空自己的23级id  及属性值列表数据
        this.category1Id = "";
        this.category2Id = "";
        this.attrList = [];

        this.category1Id = categoryId;
      } else if (level === 2) {
        // 父组件获取到2级id要清空自己的3级id  及属性值列表数据
        this.category3Id = "";
        this.attrList = [];

        this.category2Id = categoryId;
      } else {
        // 父组件获取到三级id要请求获取属性列表数据
        this.category3Id = categoryId;

        this.getAttrList();
      }
    },

    //  请求获取属性列表数据
    async getAttrList() {
      let { category1Id, category2Id, category3Id } = this;
      try {
        const result = await this.$API.attr.getList(
          category1Id,
          category2Id,
          category3Id
        );
        if (result.code === 200 || result.code === 20000) {
          this.attrList = result.data;
        }
      } catch (error) {}
    },

    // 点击展示添加页面
    showAddDiv() {
      this.isShowList = false;
      this.attrForm = {
        attrName: "",
        attrValueList: [
          // {
          //   attrId: 0,
          //   id: 0,
          //   valueName: "string",
          // },
        ],
        categoryId: this.category3Id,
        categoryLevel: 3,
      };
    },

    // 点击展示更新页面
    showUpdateDIv(row) {
      this.isShowList = false;
      // 由于属性对象当中属性值列表也是对象数据 ,浅拷贝属性值列表数据还是同一个  所以浅拷贝搞不定对象内部的对象数据
      // this.attrForm = {...row}
      this.attrForm = cloneDeep(row);
      // 修改属性当中,属性值是已经存在的
      this.attrForm.attrValueList.forEach((item) => {
        // item.isEdit = false;

        this.$set(item, "isEdit", false); //  这样添加新的属性才是响应式的
      });

      // this.attrForm.attrValueList.forEach((item)=>{
      //   this.$set(item,'isEdit',false)
      // })

    },

    // 点击添加属性值
    addAttrValue() {
      this.attrForm.attrValueList.push({
        attrId: this.attrForm.id,
        valueName: "",
        isEdit: true, //  由于是新添加的属性值,那么isEdit是true代表目前应该是编辑模式
      });
      // dom更新完成后执行回调
      this.$nextTick(() => {
        this.$refs[this.attrForm.attrValueList.length - 1].focus();
      });
    },

    // 切换为编辑模式
    toEdit(row, index) {
      row.isEdit = true;

      // 赋值完成 input 才开始创建
      this.$nextTick(() => {
        // 让对应的点击的这项自动获取焦点
        this.$refs[index].focus();
      });
    },

    // input  失去焦点  或 键盘事件  切换为查看模式
    toLook(row) {
      // 判断输入的属性值是否为空
      if (row.valueName.trim() === "") {
        row.valueName = "";
        return;
      }
      // 除了自己之外 判断输入属性值与之前的是否有重复的
      let isRepeat = this.attrForm.attrValueList.some((item) => {
        if (item !== row) {
          return item.valueName === row.valueName;
        }
      });

      if (isRepeat) {
        this.$message.success("输入的属性值不能重复");
        row.valueName = "";
        return;
      }
      row.isEdit = false;
    },

    // 点击保存
    async save() {
      let attr = this.attrForm;

      // 整理参数

      attr.attrValueList = attr.attrValueList.filter((item) => {
        if (item.valueName !== "") {
          delete item.isEdit;
          return true;
        }
      });

      if (attr.attrValueList.length === 0) {
        this.$message.info("属性的属性值不能为空");
        return;
      }

      // 发送请求
      try {
        await this.$API.attr.addOrUpdate(attr);
        this.$message.success("保存属性成功");
        this.isShowList = true; //  回到列表页
        this.getAttrList(); //  重新获取列表页数据
      } catch (error) {
        this.$$message.error("保存属性失败");
      }
    },

    // 删除属性
    async deleteAttr(row) {
      try {
        const result = await this.$API.attr.delete(row.id);
        if (result.code === 200 || result.code === 20000) {
          this.$message.success("删除属性成功");
          this.getAttrList();
        } else {
          this.$message.error("删除属性失败");
        }
      } catch (error) {
        this.$message.error("删除属性请求失败");
      }
    },
  },
};
</script>

<style lang="less" scoped>
</style>
